Kotlin

Returns and Jumps

Swift
                  val s = person.name ?: return
                
👏
                    guard let s = person.name else { return }



                  

Break and Continue Labels

                  loop@ for (i in 1..100) {
    // ...
}
                
                    loop: for i in 1...100 {
    // ...
}

                  
                  loop@ for (i in 1..100) {
    for (j in 1..100) {
        if (...) break@loop
    }
}
                
                    loop: for i in 1...100 {
    for j in 1...100 {
        if ... break loop
    }
}

                  

Return at Labels

                  fun foo() {
    listOf(1, 2, 3, 4, 5).forEach {
        if (it == 3) return // non-local return directly to the caller of foo()
        print(it)
    }
    println("this point is unreachable")
}
                
                    func foo() {
    [1, 2, 3, 4, 5].forEach {
        if $0 == 3 { return }
        print($0)
    }
    print("this point is reachable")
}

                  
                  fun foo() {
    listOf(1, 2, 3, 4, 5).forEach lit@{
        if (it == 3) return@lit // local return to the caller of the lambda, i.e. the forEach loop
        print(it)
    }
    print(" done with explicit label")
}
                
                  fun foo() {
    listOf(1, 2, 3, 4, 5).forEach {
        if (it == 3) return@forEach // local return to the caller of the lambda, i.e. the forEach loop
        print(it)
    }
    print(" done with implicit label")
}
                
                  fun foo() {
    listOf(1, 2, 3, 4, 5).forEach(fun(value: Int) {
        if (value == 3) return  // local return to the caller of the anonymous fun, i.e. the forEach loop
        print(value)
    })
    print(" done with anonymous function")
}
                
                    func foo() {
    [1, 2, 3, 4, 5].forEach(fun(value: Int) {
        if (value == 3) return  // local return to the caller of the anonymous fun, i.e. the forEach loop
        print(value)
    })
    print(" done with anonymous function")
}
                  
                  fun foo() {
    run loop@{
        listOf(1, 2, 3, 4, 5).forEach {
            if (it == 3) return@loop // non-local return from the lambda passed to run
            print(it)
        }
    }
    print(" done with nested loop")
}
                
                  return@a 1